import { createRouter, createWebHistory } from 'vue-router';
import { getCookie } from '@/utils/utils';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: () => import("@/views/HomeView.vue"),
      meta: { requiresAuth: true }, // 需要登录才能访问
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/LoginView.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () => import("@/views/RegisterView.vue"),
    }
  ]
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要登录
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth);
  // 从cookie检查是否有token
  const token = getCookie('token');
  const isLoggedIn = !!token;

  // 如果需要登录但没有token，则重定向到登录页面
  if (requiresAuth && !isLoggedIn) {
    next('/login');
  } else if ((to.path === '/login' || to.path === '/register') && isLoggedIn) {
    // 如果已有token但试图访问登录/注册页面，则重定向到主页
    next('/');
  } else {
    // 其他情况正常放行
    next();
  }
});

export default router;
